/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-12-12 16:52
 * description :
 * history :
 */

package seller

import (
    "dhfshop/models"
	"strings"
	"errors"
	"github.com/astaxie/beego/orm"
)

//分销商绩效
type Profit struct {
	PartnerId    int64     `orm:"column(partner_id);pk;auto" json:"partner_id" form:"partner_id"` //分销商编号 
	CompanyId    int64     `orm:"column(company_id)" json:"company_id" form:"company_id"`    //
	Name         string  `orm:"column(name)" json:"name" form:"name"`              //分销商名称
	SaleNumber   int32   `orm:"column(sale_number)" json:"sale_number" form:"sale_number"`  //销售笔数
	SaleIncome   float32 `orm:"column(sale_income);digits(12);decimals(2)" json:"sale_income" form:"sale_income"` /* 分销商收入*/
	ShipIncome   float32 `orm:"column(ship_income);digits(12);decimals(2)" json:"ship_income" form:"ship_income"` /* 运费收入*/
	SaleCost     float32 `orm:"column(sale_cost);digits(12);decimals(2)" json:"sale_cost" form:"sale_cost"` /* 分销商成本*/
	ShipCost     float32 `orm:"column(ship_cost);digits(12);decimals(2)" json:"ship_cost" form:"ship_cost"` /* 运费成本*/
	LastSaleTime int64   `orm:"column(last_sale_time)" json:"last_sale_time" form:"last_sale_time"`  //最后销售时间 
}

func init() {
    orm.RegisterModel(new(Profit))   
}

func AddProfit(m *Profit) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetProfitById(id int64) (v *Profit, err error) {
	o := models.GetDefaultDB()
	v = &Profit{PartnerId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllProfits(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Profit, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Profit))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Profit
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateProfitById(m *Profit, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Profit{PartnerId: m.PartnerId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteProfit(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Profit{PartnerId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
